package com.github.bryx.workflow.referenceobject;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Map;

/**
 *
 * ReferenceObjectService的官方实现
 * @Author jameswu
 * @Date 2021/7/22
 **/
@Slf4j
public class SimpleReferenceObjectServiceImpl implements ReferenceObjectService{

    static Map<Class, ReferenceObjectLoader> loaders = Maps.newHashMap();

    @Override
    public void registerLoader(Class clazz, ReferenceObjectLoader loader) {
        loaders.put(clazz, loader);
    }

    @Override
    public ReferenceObjectLoader getLoader(Class clazz) {
        return loaders.get(clazz);
    }

    public  Map<String, Map<String, Object>> loadReferenceObjects(ReferenceObjectSupport support){
        return this.loadReferenceObjects_(support.referenceObjectIds());
    }

    public Map<String, Map<String, Object>> loadReferenceObjects_(Map<Class, Collection> referenceObjectIds){
        Map<String, Map<String, Object>> rtobjects = Maps.newHashMap();
        referenceObjectIds.forEach((key, value)->{
            ReferenceObjectLoader loader = getLoader(key);
            if (loader == null){
                log.error("not found a loader for class {}", key);
            }else{
                rtobjects.put(key.getSimpleName().toLowerCase(), loader.loadObjects(key, value));
            }
        });
        return rtobjects;
    }


    public  Map<String, Map<String, Object>> loadReferenceObjects(Collection<? extends ReferenceObjectSupport> supports){
        Map<Class, Collection> referenceObjectIds = Maps.newHashMap();
        supports.forEach(support->{
            Map<Class, Collection> referenceObjectIds_ = support.referenceObjectIds();
            referenceObjectIds_.forEach((key, value)->{
                if (referenceObjectIds.containsKey(key)){
                    referenceObjectIds.get(key).addAll(value);
                }else{
                    referenceObjectIds.put(key, value);
                }
            });
        });
        return this.loadReferenceObjects_(referenceObjectIds);
    }
}
